package com.agileboot.attendance.domain.order.db;

import com.agileboot.attendance.domain.order.dto.OrderQuery;
import com.agileboot.attendance.domain.order.entity.AttOrderEntity;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author agileboot
 */
@Service
public class AttOrderService extends ServiceImpl<AttOrderMapper, AttOrderEntity> {

    /**
     * 分页查询订单列表
     *
     * @param query 查询参数
     * @return 分页结果
     */
    public Page<AttOrderEntity> getOrderList(OrderQuery query) {
        Page<AttOrderEntity> page = query.toPage();

        LambdaQueryWrapper<AttOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(query.getOrderCode()), AttOrderEntity::getOrderCode, query.getOrderCode())
                .eq(query.getProjectId() != null, AttOrderEntity::getProjectId, query.getProjectId())
                .eq(query.getSupplierId() != null, AttOrderEntity::getSupplierId, query.getSupplierId())
                .eq(StringUtils.isNotBlank(query.getStatus()), AttOrderEntity::getStatus, query.getStatus())
                .ge(StringUtils.isNotBlank(query.getBeginTime()), AttOrderEntity::getStartDate, query.getBeginTime())
                .le(StringUtils.isNotBlank(query.getEndTime()), AttOrderEntity::getStartDate, query.getEndTime())
                .orderByDesc(AttOrderEntity::getCreateTime);

        return page(page, queryWrapper);
    }

    /**
     * 检查订单编码是否重复
     *
     * @param orderCode 订单编码
     * @param orderId 订单ID（更新时使用）
     * @return 是否重复
     */
    public boolean isOrderCodeDuplicated(String orderCode, Long orderId) {
        LambdaQueryWrapper<AttOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttOrderEntity::getOrderCode, orderCode)
                .ne(orderId != null, AttOrderEntity::getOrderId, orderId);
        return count(queryWrapper) > 0;
    }
} 